<?php
/**
* 按xml方式输出通信数据
*/
class Xml extends Api
{
	/**
	 * xml
	 * @param  int $code    [description]
	 * @param  string $message [description]
	 * @param  array  $data    [description]
	 * @return string          [description]
	 */
	public function response($code, $message = '', $data = array())
	{
		if (!(is_numeric($code))) {
			return '';
		}
		$result = array(
			'code' => $code,
			'message' => $message,
			'data' => $data
		);
		header('Content-Type:text/xml;charset=utf8');
		$xml = "<?xml version='1.0' encoding='UTF-8'?>";
		$xml .= "<root>";
		$xml .= self::xmlToEncode($result);
		$xml .= "</root>";
		echo $xml;
	}
	/**
	 * xml递归
	 * @param  array $result [description]
	 * @return string         [description]
	 */
	private static function xmlToEncode($result)
	{
		$xml = $attr = '';
		foreach ($result as $key => $value) {
			if (is_numeric($key)) {
				$attr = " id='" . $key . "'";
				$key = 'item';
			}
			$xml .= "<{$key}{$attr}>";
			$xml .= is_array($value) ? self::xmlToEncode($value) : $value;
			$xml .= "</{$key}>";
		}
		return $xml;
	}
}